package com.jthinker.client.web;

import com.jthinker.base.constant.Constant;
import com.jthinker.bean.UserWrapper;
import com.jthinker.client.utils.SSOClientUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 客户端SSO
 * Created by chen.gang on 2014/12/28.
 */
public class SSOClientFilter implements Filter
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SSOClientFilter.class);

    private static final String LOG_OUT_BROADCAST = "/ssoLogOut";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String url = request.getRequestURI();

        LOGGER.info("request url {}", url);
        if (LOG_OUT_BROADCAST.equals(url))
        {
            String st = request.getParameter(Constant.ST);
            SSOClientUtils.logout(st);
            LOGGER.info("sso logout {},{}", url, st);
        }

        //是否要拦截
        if (SSOClientUtils.isEscapeUrl(url))
        {
            filterChain.doFilter(request, response);
        }
        else
        {
            UserWrapper wrapper = SSOClientUtils.getSSOUser(request);
            if (wrapper == null)
            {
                String st = request.getParameter(Constant.ST);
                if (StringUtils.isBlank(st))
                {
                    SSOClientUtils.redirectToSSOServer(request, response);
                }
                else
                {
                    wrapper = SSOClientUtils.validateST(st);
                    if (wrapper == null)
                    {
                        LOGGER.error("invalid service ticket {}", st);
                        SSOClientUtils.redirectToSSOServer(request, response);
                    }
                    else
                    {
                        SSOClientUtils.login(request, st, wrapper);
                        filterChain.doFilter(request, response);
                    }
                }
            }
            else
            {
                filterChain.doFilter(request, response);
            }
        }

    }

    @Override
    public void destroy()
    {

    }

}
